package com.augrain.microframework.web.advice;

import com.augrain.microframework.core.consts.HttpStats;
import com.augrain.microframework.core.util.BeanUtils;
import com.augrain.microframework.web.base.ApiContext;
import com.augrain.microframework.web.base.ApiResult;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.resource.NoResourceFoundException;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import java.util.Map;

/**
 * 404 handler异常解析器
 *
 * @author biaoy
 * @since 2021/03/11
 */
public class ApiExceptionHandlerResolver implements HandlerExceptionResolver, Ordered {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
                                         Exception ex) {
        if (ex instanceof NoHandlerFoundException || ex instanceof NoResourceFoundException) {
            ApiContext current = ApiContext.getCurrent();
            ApiResult apiResult =
                    ApiResult.builder().code(HttpStats.HTTP_NOT_FOUND).timestamp(System.currentTimeMillis())
                            .msg("api路径错误").api(current == null ? null : current.getApi()).build();

            // 返回json
            ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());

            Map<String, Object> apiResultMap = BeanUtils.bean2Map(apiResult);
            apiResultMap.forEach((k, v) -> modelAndView.getModel().put(k, v));
            return modelAndView;
        }
        return null;
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
